<template>
  <div class="box_list">
    <!-- 路径面包屑区域 -->
    <el-breadcrumb class="mb15">
      <el-breadcrumb-item :to="{ path: '/main' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>
        <router-link to="/goods">商品列表</router-link>
      </el-breadcrumb-item>
      <el-breadcrumb-item style="color:#ccc">新增商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 工作区域 -->
    <el-card>
      <!-- 注意 -->
      <el-alert center show-icon title="添加商品信息" type="info" :closable="false"></el-alert>
      <!-- 执行步骤提示 -->
      <el-steps :active="active" finish-status="success" align-center class="mt15 mb25">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 树形tab页 form -->
      <el-form :model="goodFormData" :rules="goodFormRules" ref="goodFormRef" label-width="150px">
        <el-tabs
          tab-position="left"
          v-model="activeName"
          @tab-click="handleClick"
          :before-leave="stopTabCut"
        >
          <el-tab-pane label="基本信息" name="0">
            <!-- 基本信息 -->
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                style="width:300px"
                v-model="goodFormData.goods_cat"
                :options="cateData"
                :props="cateProps"
                @change="handleChange"
                size="small"
              ></el-cascader>
            </el-form-item>
            <el-form-item label="商品名称" prop="goods_name" size="small">
              <el-input v-model.trim="goodFormData.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price" size="small">
              <el-input v-model.trim="goodFormData.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight" size="small">
              <el-input v-model.trim="goodFormData.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number" type="number" size="small">
              <el-input v-model="goodFormData.goods_number"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 商品参数 -->
            <el-form-item
              :label="item.attr_name+'：'"
              v-for="(item, index) in cateParameterdata"
              :key="index"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  :label="cb"
                  border
                  size="small"
                  v-for="(cb, i) in item.attr_vals"
                  :key="i"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <!-- 商品属性 -->
            <el-form-item
              :label="item.attr_name"
              v-for="(item, index) in cateAttributedata"
              :key="index"
              size="small"
            >
              <el-input v-model.trim="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- 商品图片 -->
            <el-upload
              :action="uploadUrl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :on-success="handleSuccess"
              :headers="headersToken"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器 -->
            <quill-editor
              v-model="goodFormData.goods_introduce"
            ></quill-editor>

            <el-row class="mt20 tac">
              <el-col :span="24">
                <el-button type="primary" size="small" @click="addform" icon="el-icon-s-promotion">立即提交</el-button>
                
              </el-col>
            </el-row>
            
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 上传图片查看 -->
    <el-dialog :title="'图片名称：'+pictureName" :visible.sync="pictureVisible" width="40%">
      <div class="tac">
        <img :src="pictureLook.url" alt style="width:80%" />
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 导入lodaash 中深拷贝方法
import _ from 'lodash'
export default {
  data() {
    return {
      // 执行步骤提示
      active: 0,
      // 树形tab页 数据绑定name值
      activeName: "0",
      // 商品分类数据
      cateData: [],
      // cascader 选择分类id push到cateKeys形成数组
      cateKeys: [],
      //cascader 展示商品分类配置
      cateProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
        expandTrigger: "hover",
        // 选择任意一级
        checkStrictly: true,
      },

      //表单数据对象
      goodFormData: {
        goods_name: "",
        goods_price: 1,
        goods_weight: 1,
        goods_number: 1,
        //选择所有商品分类id数组
        goods_cat: {},
        //上传图片临时路径
        pics: [],
        //富文本编辑器参数
        goods_introduce: "",
        // 商品参数动态属性
        attrs:[]
      },
      // 对应商品参数数据
      cateParameterdata: [],
      // 对应商品属性
      cateAttributedata: [],
      // 图片上传后台路径定义
      uploadUrl: "http://127.0.0.1:8888/api/private/v1/upload",

      //本地Authorization是绑定到axios请求上只有发送axios请求才会带token，element upload 自己封装的请求，所有要将 后台token要绑定到upload上面headers
      headersToken: {
        Authorization: window.sessionStorage.getItem("token"),
      },
      // 上传图片查看
      pictureLook: {},
      // 上传图片查看 ，名称
      pictureName: "",
      // 上传图片查看,窗口关闭显示
      pictureVisible: false,
      // 表单验证规则
      goodFormRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请输入商品分类", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getCateData();
  },
  methods: {
    // 获取商品分类数据
    getCateData() {
      this.$axios
        .get("categories")
        .then((res) => {
          //console.log(res);
          if (res.data.meta.status == 200) {
            this.cateData = res.data.data;
          } else {
          }
        })
        .catch((error) => {
          console.log(error); //cathch用于处理错误事件
        });
    },
    //监听商品分类选择的变化
    handleChange() {
      // 证明选中的是 三级商品分类
      if (this.goodFormData.goods_cat.length === 3) {
      } else {
        // 证明选中的不是 三级商品分类
        this.goodFormData.goods_cat = [];
        return;
      }
    },
    // 没有选择商品分类阻止tab页切换  oldActiveName即将离开的标签，activeName即将进入的标签
    stopTabCut(activeName, oldActiveName) {
      if (oldActiveName === "0" && this.goodFormData.goods_cat.length !== 3) {
        this.$message.error("请先选择商品分类，再进行其他操作");
        return false;
      }
    },
    // 监听当前tab 被选中时触发事件
    handleClick() {
      // 实现步骤和tab切换联动// 将this.activeName字符串转化成number在赋给active
      this.active = parseInt(this.activeName);
      console.log(this.activeName);
      if (this.activeName == 1) {
        this.$axios
          .get(`categories/${this.threeCateId}/attributes`, {
            params: {
              sel: "many",
            },
          })
          .then((res) => {
            if (res.data.meta.status == 200) {
              //console.log(res);
              // 通过循环数组 每循环一遍拿到当前的item，找到当前数组下的attr_vals对象，判断当前对象是否为空，为空就结束，否则将attr_vals字符串，将字符串用split 拆分，然后用空格分隔，最后传给原数组中对象item.attr_vals重新赋值
              res.data.data.forEach((item) => {
                item.attr_vals =
                  item.attr_vals.length === 0 ? [] : item.attr_vals.split(",");
              });
              this.cateParameterdata = res.data.data;
              //console.log(this.cateParameterdata)
            } else {
              this.$message.error("获取商品参数失败");
            }
          })
          .catch((error) => {
            console.log(error); //cathch用于处理错误事件
          });
      } else if (this.activeName == 2) {
        this.$axios
          .get(`categories/${this.threeCateId}/attributes`, {
            params: {
              sel: "only",
            },
          })
          .then((res) => {
            //console.log(res);
            if (res.data.meta.status == 200) {
              this.cateAttributedata = res.data.data;
            } else {
              this.$message.error("获取商品属性成功");
            }
          })
          .catch((error) => {
            console.log(error); //cathch用于处理错误事件
          });
      } else if (this.activeName == 3) {
      }
    },
    //上传图片成功查看图片
    handlePreview(file) {
      console.log(file);
      this.pictureLook = file.response.data;
      (this.pictureName = file.name), (this.pictureVisible = true);
    },
    // 上传图片成功删除图片
    handleRemove(file) {
      //删除时拿到虚拟路径下的图片路径tmp_path
      const tmp_path_upload = file.response.data.tmp_path;
      console.log(tmp_path_upload);
      // 拿到虚拟路径下的图片路径tmp_path和goodFormData中pics中的图片数组对比-相同时的索引
      const i = this.goodFormData.pics.findIndex((val, index, arr) => {
        return val.pic === tmp_path_upload;
      });
      // 将当前的索引对应的图片移除
      this.goodFormData.pics.splice(i, 1);
      //console.log(this.goodFormData)
    },
    // 图片上传成功时钩子函数 时调用 response后台接收的数据
    handleSuccess(response) {
      //console.log(response)
      // 将图片信息对象拼接后台需要格式
      const picturePath = { pic: response.data.tmp_path };
      //将图片信息拼接后对象 push到goodFormData.pics数字中
      this.goodFormData.pics.push(picturePath);
      console.log(this.goodFormData);
    },
    // 提交表单
    addform(){
      this.$refs.goodFormRef.validate((valid)=>{
        if(valid){
          //将goods_cat商品分类右数组转换成逗号相隔的字符串，然而不能直接转换，cascader商品分类中用到了双向绑定，所要先深拷贝一份出来进行操作，从而不影响页面所用到的数据
          // lodash cloneDeep(obj) 方法   https://www.lodashjs.com/javascript中文文档
          const form=_.cloneDeep(this.goodFormData);
          form.goods_cat=form.goods_cat.toString()
          // 处理动态参数 循环拿到每个attr_id，attr_value对象在填充到attrs中
          this.cateParameterdata.forEach(item=>{
            const newsInfo={attr_id:item.attr_id,attr_value:item.attr_vals.toString()}
            this.goodFormData.attrs.push(newsInfo)
          })
          // 处理静态属性 循环拿到每个attr_id，attr_value对象在填充到attrs中
          this.cateAttributedata.forEach(item =>{
            const newsInfo={attr_id:item.attr_id,attr_value:item.attr_vals}
            this.goodFormData.attrs.push(newsInfo)
          })
          //将拿到的参数和属性在赋给已拷深贝 form.attrs中提交
          form.attrs=this.goodFormData.attrs
          //console.log(form)
          this.$axios.post('goods',form)
          .then((res) => {
            console.log(res)
              if(res.data.meta.status==201){
                this.$message.success("添加商品成功")
                this.$router.push("/goods")
              }else{
                 this.$message.error("添加商品失败")
                 return
              }
          }).catch((error) => {
             console.log(error)
          });
           
        }else{
          this.$message.error("请填写必要的表单项")
          return
        }
      })
    }
  },
  computed: {
    threeCateId() {
      // 证明选中的是 三级商品分类
      if (this.goodFormData.goods_cat.length === 3) {
        return this.goodFormData.goods_cat[2];
      } else {
        // 证明选中的不是 三级商品分类
        return null;
      }
    },
  },
};
</script>
 
<style scoped>
.el-checkbox.is-bordered + .el-checkbox.is-bordered {
  margin-left: 0;
}
</style>